#include "head.h"
#include <sys/select.h>
#include <mysql/mysql.h>
int main(int argc, char *argv[])
{
    // ./00_server 192.168.72.128 12345
    ARGS_CHECK(argc,3);
    int sockfd = socket(AF_INET,SOCK_STREAM,0);
    struct sockaddr_in addr;
    addr.sin_family = AF_INET;
    addr.sin_port = htons(atoi(argv[2]));
    addr.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = bind(sockfd,(struct sockaddr *)&addr,sizeof(addr));
    ERROR_CHECK(ret,-1,"bind");
   listen(sockfd,50);
 MYSQL    *ret_db = mysql_init(NULL);
    char *host = "localhost";
    char *user = "root";
    char *password = "123";
      char *database ="wp_3" ;
 MYSQL*ret1 = mysql_real_connect(ret_db,host,user,password,database,0,NULL,0);
    if(ret1 == NULL){
        printf("Error: %s\n", mysql_error(ret_db));
        return -1;
    }
    char*sql="CREATE TABLE IF NOT EXISTS users ("
"id INT AUTO_INCREMENT PRIMARY KEY, "
"username VARCHAR(10) NOT NULL UNIQUE, "  // 添加用户名字段
"password VARCHAR(10) NOT NULL, "       // 添加密码字段
"saltNum VARCHAR(32) NOT NULL, "
"isDelete TINYINT(1) DEFAULT 0, "
"ciphertext VARBINARY(32) NOT NULL, "
"isLoggedIn TINYINT(1) DEFAULT 0)";

   char *token=(char*)malloc(65);//模拟token，需要替换为token生成函数，并且在主线程中运行

   sprintf(token,"monitoken");
     int qret = mysql_query(ret_db,sql);
    if(qret != 0){
        printf("Error: %s\n", mysql_error(ret_db));
        return -1;
    }
    fd_set readset; //读集合
     int netfd = accept(sockfd,NULL,NULL);
    while(1){
        FD_ZERO(&readset); //初始化
        FD_SET(netfd,&readset); //把通信socket加入监听
      

        if(FD_ISSET(netfd,&readset)){
 TLV*TLV_RECV=(TLV*)malloc(sizeof(TLV));
     memset(TLV_RECV,0,sizeof(TLV));      


            recvTlv(netfd,TLV_RECV);//接受注册和登录命令
                strncpy(TLV_RECV->token,token,65);
            if(TLV_RECV->type==0x41)//收到注册信号
tackle_register(netfd,ret_db,TLV_RECV);
            else if(TLV_RECV->type==0x42){//收到登陆信号
tackle_signin(netfd, ret_db,TLV_RECV);
            }


    printf("sjsjjs\n");


free(TLV_RECV);

        }



   }
    close(sockfd);
}


